<?php
// system/application/models/user.php
class User extends Doctrine_Record {
		
	public function setTableDefinition() {
		$this->hasColumn('uid', 'integer', 4, 
			array(
				'unsigned' => true,
      	'primary' => true,
				'notnull' => true,
				'default' => 0,
				'autoincrement' => true,
				'comment' => 'Llave primaria: Unico id de usuario.'
      )
    );

    $this->hasColumn('username', 'string', 60,
    	array(
				'notnull' => true,
    		'default' => '',
    		'comment' => 'Nombre del usuario.'
      )
    );
    
    $this->hasColumn('password', 'string', 128,
    	array(
				'notnull' => true,
    		'default' => '',
    		'comment' => 'password del usuario (hashed).'
      )
    );
    
    $this->hasColumn('email', 'string', 254,
    	array(
    		'notnull' => true,
    		'default' => '',
    		'comment' => 'email del usuario/User’s email address.'
      )
    );
    
    $this->hasColumn('access', 'integer', 4,
    	array(
				'notnull' => true,
    		'default' => 0,
    		'comment' => 'hora y fecha del ultimo acceso/Timestamp for previous time user accessed the site.'
      )
    );
    
    $this->hasColumn('login', 'integer', 4,
    	array(
				'notnull' => true,
    		'default' => 0,
    		'comment' => 'hora y fecha del ultimo login/Timestamp for user’s last login.'
      )
    );
    
    $this->hasColumn('status', 'integer', 1,
    	array(
				'notnull' => true,
    		'default' => 0,
    		'comment' => 'si el usuario esta activo (1) o bloqueado (0)/Whether the user is active(1) or blocked(0).'
      )
    );
	}
	
	public function setUp() {
		//$this->setTableName('user');
		$this->actAs('Timestampable');
		
		// the user is created in the client and there is created usign an MD5 function
		// so, the mutator should be removed from the server side
		//$this->hasMutator('password', '_encrypt_password');
		
		$this->hasMany('Role as roles', 
			array(
      	'local' => 'user_id',
        'foreign' => 'role_id',
				'refClass' => 'UserRole',
      )
    );
	}
	
	protected function _encrypt_password($value) {
		$this->_set('password', md5($value));
	}
	
	public function updateValues(array $data, $create = false) {
		if( isset($data['username']) ) {
			$this->username = $data['username'];
		}
		if( isset($data['encrytedPassword']) ) {
			$this->password = $data['encrytedPassword'];
		}
		if( isset($data['email']) ) {
			$this->email = $data['email'];
		}
		if( isset($data['status']) ) {
			$this->status = $data['status'] == 'on' ? 1 : 0;
		}
		if( !empty($data['roles'])) {
			try {
				// delete the roles collection
				if( !$create && $this->relatedExists('roles') ) {
					$this->UserRole->delete();
					$this->clearRelated('roles');
					/*
					$q = Doctrine_Query::create()
						->delete('UserRole') 
						->addWhere('user_id = ?', $this->uid) 
						->whereIn('role_id', array(1, 2));
					$deleted = $q->execute();
					*/
				}
				// create a collection from database
				//$dbroles = Doctrine_Core::getTable('Role')->findAll();
				$roles = explode(',', $data['roles']);
				foreach( $roles as $role) {
					//$this->roles[] = $dbroles[((int)$role) - 1];
					$userRole = new UserRole(); 
					$userRole->user_id = $this->uid; 
					$userRole->role_id = $role; 
					$userRole->save();	
				}
				
			} catch (Doctrine_Exception $e) {
				throw $e;
			}
		}
	}

	/**
	 * 
	 * @return array of permissions
	 */
	public function getPermissionsName() {
		$conn = Doctrine_Manager::connection();
			
		$query = 'select p.permission from sismapc.permission p 
			inner join sismapc.roles_permissions rp on rp.permission_id = p.id
			inner join sismapc.role r on rp.role_id = r.id
			inner join sismapc.users_roles ur on r.id = ur.role_id
			inner join sismapc.user u on ur.user_id = u.uid
			where u.uid = '.$this->uid;
		
		$statement = $conn->prepare($query); 
		$statement->execute(); 
		$results = $statement->fetchAll(); 
	  $perms = array();
	  foreach( $results as $result ) {
	   	$perms[] = $result['permission'];	
	  }
	  
	  return $perms;	
	}
	
	public function getRolesName() {
		$rolesArray = null;
		
		if( !isset($this->roles) ) {
			$this->refresh();
			$this->refreshRelated();
		}
		
		$result = $this->toArray();
		if( isset($result['roles']) ) {
  		$roles = $result['roles'];
  		unset($result['roles']);
  		
  		$rolesArray = array();
	  	foreach ($roles as $role)	{
	  		$rolesArray[] = $role['name'];
	  	}
  	}
		return $rolesArray;
	}
}